package com.wanxi.spring.cloud.permission.service.impl;

import com.wanxi.spring.cloud.commons.api.CommonResult;
import com.wanxi.spring.cloud.permission.mapper.PermissionMapper;
import com.wanxi.spring.cloud.permission.model.Permission;
import com.wanxi.spring.cloud.permission.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 蒋帆
 * @since 2020-12-21
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired(required = false)
    PermissionMapper permissionMapper;

    @Override
    public CommonResult getPermissions(Integer page, Integer limit) {
        page=(page-1)*limit;
        List<Permission> permissions = permissionMapper.getPermissions(page,limit);
        long count = permissionMapper.getPermissionsCount();
        return CommonResult.success(permissions,count);
    }

    @Override
    public CommonResult addPermission(Permission permission) {
        try {
            permissionMapper.addPermission(permission);
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed("添加失败");
        }
        return CommonResult.success(true,"添加成功！");
    }

    @Override
    public CommonResult updatePermission(Permission permission) {
        try {
            permissionMapper.updatePermission(permission);
        }catch (Exception e){
            return CommonResult.failed("修改失败");
        }
        return CommonResult.success(true,"修改成功！");
    }

    @Override
    public CommonResult deletePermission(Integer id) {
        try {
            permissionMapper.deletePermission(id);
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed("删除失败");
        }
        return CommonResult.success(true,"删除成功！");
    }

    @Override
    public CommonResult getAllPermissions() {
        List<Permission> permissions = permissionMapper.getAllPermissions();
        return CommonResult.success(permissions);
    }

    @Override
    public CommonResult getPermissions(Map map) {
        int page = (Integer.parseInt((String) map.get("page")) - 1) * Integer.parseInt((String) map.get("limit"));
        map.put("page", page);
        map.put("limit", Integer.parseInt((String) map.get("limit")));
        List<Permission> permissions = permissionMapper.getPermissions(map);
        long count = permissionMapper.getPermissionsCount(map);
        return CommonResult.success(permissions,count);
    }
}
